package ctd.dome.sync;

/**
 * 处理数据脏读问题:
 * 业务整体需要使用完整的synchronized,保持业务的原子性
 * Created by houxr on 2017/4/21 15:31.
 */
public class DirtyRead {
    private String username = "houxiurong";
    private String password = "09012326";

    //添加 同步锁 synchronized
    public synchronized void setValue(String username, String password) {
        this.username = username;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.password = password;
        System.out.println("setValue最终结果:username=" + username + ",password=" + password);
    }

    public void getValue() {
        System.out.println("getValue获取结果:username=" + this.username + ",password=" + this.password);
    }

    public static void main(String[] args) throws Exception {
        final DirtyRead dirtyRead = new DirtyRead();
        Thread t1 = new Thread(new Runnable() {

            public void run() {
                dirtyRead.setValue("李四", "123456");
            }
        });
        t1.start();
        Thread.sleep(1000);
        dirtyRead.getValue();
    }

}
